
#include "wormnet/wm_string.h"
#include "wmLogs.h"
#include <assert.h>
#include <sstream>
#include "wormnet/wm_string.h"
#include "wormnet/wm_std.h"
#include <glog/logging.h>

namespace worm
{

wmLogs::wmLogs()
{
    m_queueLogs = new std::queue<SLog*>;

    RakNet::RakThread::Create(&wmLogs::HandleLogsQueue, this);
}

wmLogs::~wmLogs()
{
    delete m_queueLogs;
    m_queueLogs = NULL;
}

void wmLogs::Initialize(const uint8& byLogLevel)
{
    if (byLogLevel < google::FATAL)
    {
        m_byLogsLevel = google::WARNING;
    }
    else
    {
        m_byLogsLevel = google::FATAL;
    }
}

void wmLogs::AddLog(SLog* pLog)
{
    m_oLock.Lock();
    m_queueLogs->push(pLog);
    m_oLock.Unlock();
}

RAK_THREAD_DECLARATION(wmLogs::HandleLogsQueue)
{
    assert(NULL != arguments);
    wmLogs* pThis = (wmLogs*)arguments;
    SLog* pLog = NULL;

    for (; !pThis->m_bStop;)
    {
#ifdef _DEBUG
        Sleep(5);
#else
        Sleep(2);
#endif //
        pThis->m_oLock.Lock();
        for (; !pThis->m_queueLogs->empty();)
        {
            pLog = pThis->m_queueLogs->front();
            pThis->m_queueLogs->pop();
            pThis->PrintLog(pLog);
            delete pLog;
            pLog = NULL;
        }
        pThis->m_oLock.Unlock();
    }

    return 0;
}

void wmLogs::PrintLog(SLog* pLog)
{
    uint32 dwLogSize = strlen(pLog->m_szLog);
    char* pOutLog = 
#ifdef WIN32
    new char[dwLogSize+1];
    ToGBK(pLog->m_szLog, dwLogSize, pOutLog);
#else
    new char[dwLogSize*3+1];
    ToUtf8(pLog->m_szLog, dwLogSize, pOutLog);
#endif // ifdef WIN32

    switch (pLog->m_byLogLvl)
    {
    case google::WARNING:
        LOG(WARNING) << pOutLog;
        break;
    case google::ERROR:
        LOG(ERROR) << pOutLog;
        break;
    case google::FATAL:
        LOG(FATAL) << pOutLog;
        break;
    default:
        LOG(INFO) << pOutLog;
        break;
    }
    

    delete []pOutLog;
    pOutLog = NULL;
}

void wmLogs::Release()
{
    m_bStop = true;
}

}
